package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.service.MemberService;
import com.xrit.sunnyday.service.OrderService;
import com.xrit.sunnyday.service.ReportService;
import com.xrit.sunnyday.service.SetmealService;
import com.xrit.sunnyday.utils.DateUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    //    会员折线图
    @GetMapping("/getMemberReport")
    public Result getMemberReport() {
        //前面12个月的数据  前端是数组
        List<String> months = new ArrayList<String>();
        //用Java中的calendar来操作日历  日历对象  calendar日历
        Calendar calendar = Calendar.getInstance();
        //设置过去一年的时间  年月日时分秒
        calendar.add(Calendar.YEAR, -1);
        //构建数据
        for (int i = 0; i < 12; i++) {
            try {
                //每次增加一个月
                calendar.add(Calendar.MONTH, 1);
                //过去的日期，设置好的日期
                Date date = calendar.getTime();
                //转换为跟数据库类型相同的
//                String dateString = DateUtils.parseDate2String(date);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = dateFormat.format(date);
                //添加到list集合
                months.add(dateString);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        //调用服务查询
        List<Integer> memberCount=memberService.getMemberReport(months);
        //添加到map
        Map<String, Object> map = new HashMap<>();
        map.put("months",months);
        map.put("memberCount",memberCount);

        //返回前端
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }

    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){
        //调用方法查询套餐预约占比
        List<Map<String,Object>> setmealCount=setmealService.findSetmealCount();
        //定义一个map
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("setmealCount",setmealCount);

        //定义一个list集合
        List<String> setmealNames=new ArrayList<>();

        //遍历map集合 拿到name
        for (Map<String, Object> map : setmealCount) {
            String name = (String) map.get("name");
            setmealNames.add(name);
        }
        hashMap.put("setmealNames",setmealNames);

        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,hashMap);
    }

    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() throws Exception {
        Map<String,Object> map=reportService.findBusinessReportData();
        return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
    }

    @GetMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest req, HttpServletResponse res) throws Exception {
        //获取运营数据统计的数据
            Map<String,Object> reportData=reportService.findBusinessReportData();
        //获取模板的路径
        String template = req.getSession().getServletContext().getRealPath("/template/report_template.xlsx");
        //创建
        try (FileInputStream fis = new FileInputStream(template);
             OutputStream os = res.getOutputStream();
             //创建工作
             XSSFWorkbook wk = new XSSFWorkbook(fis)){
            //获取表格
            XSSFSheet sht = wk.getSheetAt(0);
            // 日期 坐标 2,5
            sht.getRow(2).getCell(5).setCellValue(reportData.get("reportDate").toString());

            //======================== 会员 ===========================
            // 新增会员数 4,5
            sht.getRow(4).getCell(5).setCellValue((Integer)reportData.get("todayNewMember"));
            // 总会员数 4,7
            sht.getRow(4).getCell(7).setCellValue((Integer)reportData.get("totalMember"));
            // 本周新增会员数5,5
            sht.getRow(5).getCell(5).setCellValue((Integer)reportData.get("thisWeekNewMember"));
            // 本月新增会员数 5,7
            sht.getRow(5).getCell(7).setCellValue((Integer)reportData.get("thisMonthNewMember"));

            //=================== 预约 ============================
            sht.getRow(7).getCell(5).setCellValue((Integer)reportData.get("todayOrderNumber"));
            sht.getRow(7).getCell(7).setCellValue((Integer)reportData.get("todayVisitsNumber"));
            sht.getRow(8).getCell(5).setCellValue((Integer)reportData.get("thisWeekOrderNumber"));
            sht.getRow(8).getCell(7).setCellValue((Integer)reportData.get("thisWeekVisitsNumber"));
            sht.getRow(9).getCell(5).setCellValue((Integer)reportData.get("thisMonthOrderNumber"));
            sht.getRow(9).getCell(7).setCellValue((Integer)reportData.get("thisMonthVisitsNumber"));

            // 热门套餐
            List<Map<String,Object>> hotSetmeal = (List<Map<String,Object>> )reportData.get("hotSetmeal");
            int row = 12;
            for (Map<String, Object> setmealMap : hotSetmeal) {
                sht.getRow(row).getCell(4).setCellValue((String)setmealMap.get("name"));
                sht.getRow(row).getCell(5).setCellValue((Long)setmealMap.get("setmeal_count"));
                BigDecimal proportion = (BigDecimal) setmealMap.get("proportion");
                sht.getRow(row).getCell(6).setCellValue(proportion.doubleValue());
                sht.getRow(row).getCell(7).setCellValue((String)setmealMap.get("remark"));
                row++;
            }
            String filename = "运营统计数据报表.xlsx";
            // 解决下载的文件名 中文乱码
            filename = new String(filename.getBytes(), "ISO-8859-1");

            // 设置头信息，告诉浏览器，是带附件的，文件下载
            res.setHeader("Content-Disposition","attachement;filename=" + filename);
            // 设置内容体的文件格式是excel
            res.setContentType("application/vnd.ms-excel");
            wk.write(os);
            os.flush();

        }catch (IOException e) {
            e.printStackTrace();
        }


    }
}
